package com.nameless.controller.api;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.nameless.annotation.HasPermission;
import com.nameless.annotation.MyLog;
import com.nameless.entity.Users;
import com.nameless.service.UserService;
import com.nameless.util.JwtUtil;
import com.nameless.util.WebUtils;
import com.nameless.vo.Result;
import com.nameless.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author keluoyisi
 */
@Api(value = "system/api/admin", tags = {"用户控制层"})
@RestController
@RequestMapping("system/api/admin")
public class ApiAdminController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @ApiOperation(value = "", notes = "")
    @Bean
    private PasswordEncoder passwordEncoder(){
       return new BCryptPasswordEncoder();
    }

    /**
     * author chh
     * 获取用户信息
     * @return {@link Result}<{@link Users}>
     */
    @ApiOperation(value = "author chh 获取用户信息", notes = "author chh 获取用户信息")
    @RequestMapping("/info")
    public Result<Users> getInfo(){
        HttpServletRequest request = WebUtils.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> tokenChaim = JwtUtil.getTokenChaim(token);
        String username = tokenChaim.get("username").toString();
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUserName,username);
        Users users = userService.getOne(queryWrapper);
        return new Result<>(200,"查询信息成功",users);
    }

    /**
     * author chh
     * 注销
     * @return {@link Result}
     */
    @ApiOperation(value = "author chh 注销", notes = "author chh 注销")
    @RequestMapping("/logout")
    public Result logout(){
        String token = WebUtils.getRequest().getHeader("token");
        System.out.println(token);
        redisTemplate.delete(token);
        return new Result(200,"退出成功");
    }

    /**
     * author chh
     * 修改密码
     * @param password    密码
     * @param newPassword 新密码
     * @return {@link Result}
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "password", value = "密码", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "newPassword", value = "新密码", required = true)
    })
    @ApiOperation(value = "author chh 修改密码", notes = "author chh 修改密码")
    @RequestMapping("/modifyPassword/{password}/{newPassword}")
    public Result modifyPassword(@PathVariable String password,@PathVariable String newPassword){
        String token = WebUtils.getRequest().getHeader("token");
        Map<String, Object> tokenChaim = JwtUtil.getTokenChaim(token);
        String username = (String) tokenChaim.get("username");
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUserName,username);
        Users users = userService.getOne(queryWrapper);
        if(password!=null && newPassword!=null){
            if (passwordEncoder().matches(password,users.getPassword())||password.equals(users.getPassword())){
                users.setPassword(passwordEncoder().encode(newPassword));
                boolean b = userService.updateById(users);
                return b?new Result(200,"修改成功"):new Result(500,"修改失败");
            }else {
                return new Result(500,"原密码错误");
            }
        }
        return new Result(500,"密码不能为空");

    }

    /**
     * Author chh
     * 修改个人信息
     * @param user 用户
     * @return {@link Result}
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "Users", name = "user", value = "用户", required = true)
    })
    @ApiOperation(value = "Author chh 修改个人信息", notes = "Author chh 修改个人信息")
    @RequestMapping("/user")
    @MyLog(title = "修改用户",businessType = 2)
    public Result updateUser(@RequestBody Users user){
        boolean b = userService.updateById(user);
        return new Result(200,"修改成功");
    }

    /**
     * 查询所有用户信息
//     * @param pageNo   页面没有
//     * @param pageSize 页面大小
     * @return {@link Result}
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "UserVo", name = "userVo", value = "", required = true)
    })
    @ApiOperation(value = "查询所有用户信息 @param pageNo   页面没有 @param pageSize 页面大小", notes = "查询所有用户信息 @param pageNo   页面没有 @param pageSize 页面大小")
    @RequestMapping("/queryAllUsers")
    @HasPermission("system:user:query")

    public Result queryAll(UserVo userVo){
        Page<Users> page = new Page<>(userVo.getPageNo(), userVo.getPageSize());
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Users::getUserId);
        wrapper.like(StringUtils.isNotEmpty(userVo.getLoginName()),Users::getLoginName,userVo.getLoginName());
        wrapper.like(StringUtils.isNotEmpty(userVo.getEmail()),Users::getEmail,userVo.getEmail());
        wrapper.like(StringUtils.isNotEmpty(userVo.getPhoneNumber()),Users::getPhonenumber,userVo.getPhoneNumber());
        wrapper.like(StringUtils.isNotEmpty(userVo.getUserName()),Users::getLoginName,userVo.getUserName());
        Page<Users> page1 = userService.page(page, wrapper);
        return new Result(200,"查询成功",page1);
    }

    /**
     * author chh
     * 通过用户id删除
     * @param userId 用户标识
     * @return {@link Result}
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "userId", value = "用户标识", required = true)
    })
    @ApiOperation(value = "author chh 通过用户id删除", notes = "author chh 通过用户id删除")
    @RequestMapping("deleteById")
    @HasPermission("system:user:remove")
    public Result deleteById(Integer userId){
        boolean b = userService.removeById(userId);
        return new Result(200,"删除成功");
    }

    /**
     * Author chh
     * 添加用户
     * @param user 用户
     * @return {@link Result}
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "Users", name = "user", value = "用户", required = true)
    })
    @ApiOperation(value = "Author chh 添加用户", notes = "Author chh 添加用户")
    @RequestMapping("insert")
    @HasPermission("system:user:add")
    public Result insert(@RequestBody Users user){
        String encode = passwordEncoder().encode(user.getPassword());
        user.setPassword(encode);
        userService.save(user);
        return new Result(200,"添加成功");
    }

    /**
     * @Author chh
     * 更新
     * @param users 用户
     * @return {@link Result}
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "Users", name = "users", value = "用户", required = true)
    })
    @ApiOperation(value = "更新", notes = "更新")
    @RequestMapping("update")
    @HasPermission("system:user:edit")
    public Result update(@RequestBody Users users){
        userService.updateById(users);
        return new Result(200,"修改成功");
    }
}